<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\QueryException;

use App\Http\Models\AccountsModel;
use App\Http\Models\TokenModel;
use App\Http\Models\SMSModel;
use App\Http\Models\SMSTimesModel;
use App\Http\Models\VerifyCodeModel;
use App\Http\Models\ActionLogModel;
use Mockery\Exception;

class AccountsController extends Controller
{

    public function __construct()
	{
		parent::__construct();
	}

	// 登录
    public function login(Request $request)
	{
		try{
			$this->validate($request, [
				'username' => 'required',
				'password' => 'required'
			]);

			$username = $request->input('username', '');
			$password = $request->input('password', '');

				if(is_email($username)) {
					//check email
					$user = AccountsModel::loginByEmail($username, $password);
				} elseif (is_mobile($username)) {
					//check phone
					$user = AccountsModel::loginByMobile($username, $password);
				}else {
					return response()->json(build_result('', '20001'));
				}
	
				if(null === $user ) {
					return response()->json(build_result('', '21001'));
				}
				
				//create token
				$token = create_token($user->guid);
				if(TokenModel::set_token($token, $user->id)){
					ActionLogModel::log('1101', $token, 'login', $user->id, $request->server('REMOTE_ADDR'));
					return response()->json(build_result(['token'=>$token]));
				}

				return response()->json(build_result('', '10002'));

		}catch(\Exception $e) {
			if($e instanceof ValidationException) {
				return response()->json(build_result('', '20001', $e->getMessage()));
			} elseif ($e instanceof QueryException) {
				return response()->json(build_result('', '10001', $e->getMessage()));
			} elseif($e instanceof \PDOException) {
				return response()->json(build_result('', '10001', $e->getMessage()));
			} else {
				return response()->json(build_result('', '10002', $e->getMessage()));
			}
		}

		
	}

	//注销
    public function logout(Request $request)
	{
		try{
			$this->validate($request, [
				'token' => 'required'
			]);
			$token = $request->input('token', '');
			TokenModel::del_token($token);
			ActionLogModel::log('1104', $token, 'logout', 0, $request->server('REMOTE_ADDR'));
			return response()->json(build_result(['token'=>$token]));
		}catch(\Exception $e){
			if($e instanceof ValidationException) {
				return response()->json(build_result('', '20001', $e->getMessage()));
			} else {
				return response()->json(build_result('', '10002', $e->getMessage()));
			}
		}
	}

	// 获取验证码
	public function getRegisterCode(Request $request)
	{
		try{
			$this->validate($request, [
				'mobile' => 'required'
			]);
			$mobile = $request->input('mobile', '');

			if(!is_mobile($mobile)) {
				return response()->json(build_result('', '20002', ''));
			}

			// 检查Ucenter Member中是否存在已验证的手机号用户
			$user = AccountsModel::checkMobile($mobile);

			if( $user ) {
				return response()->json(build_result('', '21002'));
			}

			$ip = $request->server('REMOTE_ADDR');

			//检查发送限制 1 IP(<100/d) 2 mobile(<5/d)
			if(SMSTimesModel::get_ip_times($ip) > 100 || SMSTimesModel::get_mobile_times($mobile) > 5) { 
				return response()->json(build_result('', '20003', ''));
			}

			$type = 'regist';
			//是否存在已经发送的注册验证嘛，如果存在，直接返回
			$verifyCodeModel = new VerifyCodeModel();
			$verifyInfo = $verifyCodeModel->get_key($type, $mobile);

			if($verifyInfo === '') {
				// 不存在 
				$verifyInfo = $verifyCodeModel->create($type, $mobile);
			}
			
			//发送验证码，并记录日志，发送次数，以及生成随机code返回
			$isSend = SMSModel::send($mobile, $type, $verifyInfo['code']);
			$isSend = '0';

			ActionLogModel::log(27, '给'.$mobile .'发送了注册验证码短信', $type, 0, $ip);
			
			if($isSend === '0') {
				SMSTimesModel::add_ip_times($ip);
				SMSTimesModel::add_mobile_times($mobile);
				return response()->json(build_result(["key" => $verifyInfo['key']]));
			} else {
				return response()->json(build_result('', '20004', ''));
			}
			
		}catch(\Exception $e) {
			return response()->json(build_result('', '20001', get_class($e).$e->getMessage()));
		}
	
	}

	// 注册
	public function register(Request $request)
	{
		try{	
			$this->validate($request, [
				'key' => 'required',
				'code' => 'required',
				'mobile' => 'required',
				'password' => 'required'
			]);

			$type = 'regist';

			$key = $request->input('key', '');
			$code = $request->input('code', '');
			$mobile = $request->input('mobile', '');
			$password = $request->input('password', '');

			$ip = $request->server('REMOTE_ADDR');

			$verifyCodeModel = new VerifyCodeModel;
			if($verifyCodeModel->verify($type, $mobile, $key, $code)){
				// register
				$AccountObj = AccountsModel::register($mobile, $password, $ip);
				if (isset($AccountObj->guid)) {
					ActionLogModel::log('1102', $AccountObj->guid, 'register', $AccountObj->id, $ip);
					return response()->json(build_result(["guid"=>$AccountObj->guid]));
				}

			} else {
				return response()->json(build_result('', '20005', ''));
			}
		}catch(\Exception $e){
			return response()->json(build_result('', '20001', get_class($e).$e->getMessage()));
		}

	}

	// 获取忘记密码的的验证码
	public function getForgetpwdCode( Request $request)
	{
		try
		{
			$this->validate($request, [
				'mobile' => 'required'
			]);
			
			$mobile = $request->input('mobile', '');

			if(!is_mobile($mobile)) {
				return response()->json(build_result('', '20002', ''));
			}

			// 检查Ucenter Member中是否存在已验证的手机号用户
			$user = AccountsModel::checkMobile($mobile);

			if(!$user) {
				return response()->json(build_result('', '20002'));
			}

			if(1 != $user->verify_mobile){
			    return response()->json(build_result('', '20002', ''));
            }

			$ip = $request->server('REMOTE_ADDR');

			//检查发送限制 1 IP(<100/d) 2 mobile(<5/d)
			if(SMSTimesModel::get_ip_times($ip) > 100 || SMSTimesModel::get_mobile_times($mobile) > 5) { 
				return response()->json(build_result('', '20003', ''));
			}

			$type = 'reset'; // 忘记密码
			//是否存在已经发送的重置密码验证嘛，如果存在，直接返回
			$verifyCodeModel = new VerifyCodeModel();
			$verifyInfo = $verifyCodeModel->get_key($type, $mobile);

			if($verifyInfo === '') {
				// 不存在 
				$verifyInfo = $verifyCodeModel->create($type, $mobile);
			}
			
			//发送验证码，并记录日志，发送次数，以及生成随机code返回
			$isSend = SMSModel::send($mobile, $type, $verifyInfo['code']);
			$isSend = '0';

			ActionLogModel::log(27, '给'.$mobile .'发送了找回密码验证码短信', $type, 0, $ip);
			
			if($isSend === '0') {
				SMSTimesModel::add_ip_times($ip);
				SMSTimesModel::add_mobile_times($mobile);
				return response()->json(build_result(["key" => $verifyInfo['key']]));
			} else {
				return response()->json(build_result('', '20004', ''));
			}
		} catch( \Exception $e) {
			return response()->json(build_result('', '20001', get_class($e).$e->getMessage()));
		}
	}

	// 重置密码
	public function resetpwd( Request $request )
	{
		try{	
			$this->validate($request, [
				'key' => 'required',
				'code' => 'required',
				'mobile' => 'required',
				'password' => 'required'
			]);

			$type = 'reset';

			$key = $request->input('key', '');
			$code = $request->input('code', '');
			$mobile = $request->input('mobile', '');
			$password = $request->input('password', '');

			$ip = $request->server('REMOTE_ADDR');

			$verifyCodeModel = new VerifyCodeModel;
			if($verifyCodeModel->verify($type, $mobile, $key, $code)){
				// update password
				$AccountObj = AccountsModel::updatePwd($mobile, $password);
				return response()->json(build_result(["reset" => $AccountObj]));
			} else {
				return response()->json(build_result('', '20005', ''));
			}
		}catch(\Exception $e){
			return response()->json(build_result('', '20001', get_class($e).$e->getMessage()));
		}
	}
}
